package com.example.storage;

import static com.github.mikephil.charting.components.Legend.LegendHorizontalAlignment.RIGHT;
import static Breakfast.Breakfast.getTodayBreakfastItems;
import static Dinner.Dinner.getTodayDinnerItems;
import static Lunch.Lunch.getTodayLunchItems;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import AboutAPP.Aboutapp;
import Breakfast.Breakfast;
import Clock.MealReminderReceiver;
import Dinner.Dinner;
import Lunch.Lunch;
import MySQL.Login;
import Robot.robot;
import Map.map;
import mealhistory.MealHistory;
import mealhistory.Mealitem;

public class MainActivity extends AppCompatActivity {

    private Mealdatabase mealhelper;
    private BottomNavigationView bottomNavigationView;
    private PieChart pieChart_today;
    private BarChart barChart_today;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0,0);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mealhelper = new Mealdatabase(this, "MEALSTORE.db", null, 3); // 创建数据库

        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.navigation_view);

        // 设置侧滑菜单的头部信息
        View headerView = navigationView.getHeaderView(0);
        TextView navUsername = headerView.findViewById(R.id.nav_header_username);
        TextView navPhone = headerView.findViewById(R.id.nav_header_phone);
        TextView navEmail = headerView.findViewById(R.id.nav_header_email);

        SharedPreferences sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        navUsername.setText(sharedPreferences.getString("username", "Username"));
        navPhone.setText(sharedPreferences.getString("phone", "Phone"));
        navEmail.setText(sharedPreferences.getString("email", "Email"));

        // 设置侧滑菜单项的点击事件
        navigationView.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_logout) {
                logout();
                return true;
            }
            else if(id == R.id.button_test_alarm){
                Log.d("TAG", "手动触发广播接收器");
                Intent intent = new Intent(MainActivity.this, MealReminderReceiver.class);
                intent.putExtra("MEAL_TIME", "饭");
                sendBroadcast(intent);
            }
            else if(id == R.id.button_chat){
                Intent intent = new Intent(MainActivity.this, robot.class);
                startActivity(intent);
            }
            else if(id == R.id.button_map){
                Intent intent = new Intent(MainActivity.this, map.class);
                startActivity(intent);
            }
            else if(id == R.id.button_recipe){
                Intent intent = new Intent(MainActivity.this, recipe.class);
                startActivity(intent);
            }
            else if(id == R.id.button_about){
                Intent intent = new Intent(MainActivity.this, Aboutapp.class);
                startActivity(intent);
            }
            return false;
        });

        // 打开侧滑菜单按钮
        ImageButton button_all = findViewById(R.id.button_nav_left);
        button_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(navigationView);
            }
        });


        //通知功能
        setMealReminder(this, 7, 30, "早餐");
        setMealReminder(this, 12, 30, "午餐");
        setMealReminder(this, 17, 30, "晚餐");


        show_navigate();

        pieChart_today = findViewById(R.id.pieChart_today);
        barChart_today = findViewById(R.id.barChart_last7days);
        setupPieChart(pieChart_today, barChart_today);
    }

    private void setMealReminder(Context context, int hour, int minute, String mealTime) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent intent = new Intent(context, MealReminderReceiver.class);
        intent.putExtra("MEAL_TIME", mealTime);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, hour, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);

        if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 1); // 如果时间已过，设置为下一天
        }

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    private void show_navigate() {
        bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setSelectedItemId(R.id.nav_main);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_main) {
                // 当前已在此活动，无需操作
                return true;
            } else if (id == R.id.nav_breakfast) {
                startActivity(new Intent(this, Breakfast.class));
                return true;
            } else if (id == R.id.nav_lunch) {
                startActivity(new Intent(this, Lunch.class));
                return true;
            } else if (id == R.id.nav_dinner) {
                startActivity(new Intent(this, Dinner.class));
                return true;
            } else if (id == R.id.nav_history) {
                startActivity(new Intent(this, MealHistory.class));
                return true;
            }
            return false;
        });
    }

    @Override
    protected void onResume() {
        overridePendingTransition(0,0);
        super.onResume();

        mealhelper = new Mealdatabase(MainActivity.this, "MEALSTORE.db", null, 3);
        setupPieChart(pieChart_today, barChart_today);
        show_navigate();
    }

    private void logout() {
        SharedPreferences sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear(); // 清除所有保存的数据
        editor.apply();

        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(MainActivity.this, Login.class);
        startActivity(intent);
        finish(); // 结束当前活动
    }

    public void setupPieChart(PieChart pieChart, BarChart barChart) {
        List<PieEntry> entries = new ArrayList<>();

        List<Mealitem> breakfastItems = getTodayBreakfastItems(this);
        float breakfast_heat = 0;
        for (Mealitem breakfastitem : breakfastItems) {
            breakfast_heat += breakfastitem.getConsumption();
        }

        List<Mealitem> lunchItems = getTodayLunchItems(this);
        float lunch_heat = 0;
        for (Mealitem lunchitem : lunchItems) {
            lunch_heat += lunchitem.getConsumption();
        }

        List<Mealitem> dinnerItems = getTodayDinnerItems(this);
        float dinner_heat = 0;
        for (Mealitem dinneritem : dinnerItems) {
            dinner_heat += dinneritem.getConsumption();
        }

        entries.add(new PieEntry(breakfast_heat, "早餐"));
        entries.add(new PieEntry(lunch_heat, "午餐"));
        entries.add(new PieEntry(dinner_heat, "晚餐"));

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setDrawValues(true);
        dataSet.setValueTextColor(Color.WHITE); // 设置数值颜色
        dataSet.setValueTextSize(12f); // 设置数值大小
        dataSet.setHighlightEnabled(true); // 启用高亮效果
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(Color.parseColor("#63b2ee"));
        colors.add(Color.parseColor("#76da91"));
        colors.add(Color.parseColor("#f8cb7f"));
        dataSet.setColors(colors);
        pieChart.getDescription().setEnabled(false);
        pieChart.getLegend().setHorizontalAlignment(RIGHT);
        pieChart.setCenterText("总消耗\n" + (breakfast_heat + lunch_heat + dinner_heat) + "kcal");

        PieData data = new PieData(dataSet);
        pieChart.setData(data);
        pieChart.invalidate(); // 刷新图表

        //下面是柱状图
        Map<String, Float> weekCalories = mealhelper.getCaloriesLastSevenDays();
        List<BarEntry> entries_2 = new ArrayList<>();
        List<String> dates = new ArrayList<>(weekCalories.keySet());
        Collections.sort(dates);  // 确保日期是按升序排列，最近七天

        SimpleDateFormat dateFormatInput = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormatOutput = new SimpleDateFormat("MM-dd");
        for (int i = 0; i < dates.size(); i++) {
            entries_2.add(new BarEntry(i, weekCalories.get(dates.get(i))));
        }

        BarDataSet dataSet_2 = new BarDataSet(entries_2, "Daily Calories");
        ArrayList<Integer> colors_2 = new ArrayList<>();
        colors_2.add(Color.parseColor("#FF0000"));
        colors_2.add(Color.parseColor("#DB3E00"));
        colors_2.add(Color.parseColor("#B86B00"));
        colors_2.add(Color.parseColor("#946000"));
        colors_2.add(Color.parseColor("#717900"));
        colors_2.add(Color.parseColor("#4B9100"));
        colors_2.add(Color.parseColor("#00FF00"));
        dataSet_2.setColors(colors_2);
        dataSet_2.setHighlightEnabled(true);

        BarData data_2 = new BarData(dataSet_2);
        barChart.setData(data_2);
        barChart.getDescription().setEnabled(false);
        barChart.getLegend().setEnabled(false);

        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(new ArrayList<String>() {{
            for (String date : dates) {
                try {
                    add(dateFormatOutput.format(dateFormatInput.parse(date)));
                } catch (ParseException e) {
                    Log.e("MainActivity", "Date parsing error", e);
                }
            }
        }}));

        barChart.invalidate(); // 刷新图表
    }
}
